package com.neuedu.jdboot.admin.controller;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.neuedu.jdboot.bean.Admin;
import com.neuedu.jdboot.bean.Role;
import com.neuedu.jdboot.common.JdbootException;
import com.neuedu.jdboot.common.Pager;
import com.neuedu.jdboot.common.Result;
import com.neuedu.jdboot.service.AdminService;
import com.neuedu.jdboot.service.RoleService;
import com.neuedu.jdboot.util.PasswordUtils;

/**
 * 
 * @author chens
 *
 */
@Controller
@RequestMapping("/sys/admin")
public class AdminController {
	private Logger logger = LoggerFactory.getLogger(AdminController.class);

	@Value("${web.upload.path}")
	private String fileRootPath;

	@Autowired
	private AdminService adminService;

	@Autowired
	private RoleService roleService;

	@RequestMapping("/list")
	public ModelAndView list(@RequestParam(name = "page", defaultValue = "1") Integer page,
			@RequestParam(name = "size", defaultValue = "10") Integer size) {
		ModelAndView view = new ModelAndView("admin/admin-list");

		Pager<Admin> pager = new Pager<>(page, size);
		// 不传递pager参数，接口方法会查询出所有的数据
		List<Admin> list = adminService.findByPager(null);
		int total = adminService.findTotal(pager);

		pager.setRows(list);
		pager.setTotal(total);

		// 使用modelAndView对象传递数据到jsp页面，jsp页面取出数据并显示
		view.addObject("pager", pager);

		return view;
	}

	@GetMapping("/add")
	public String toAdd(Model model) {
		List<Role> roles = roleService.findList();

		model.addAttribute("roleList", roles);
		return "admin/admin-add";
	}

	@GetMapping("/edit/{id}")
	public String toEdit(@PathVariable(value = "id") Integer id, Model model) {
		List<Role> roles = roleService.findList();

		Admin admin = adminService.findById(id);

		model.addAttribute("roleList", roles);
		model.addAttribute("admin", admin);
		return "admin/admin-edit";
	}

	@PostMapping("/add")
	@ResponseBody
	public Result doAdd(Admin admin, MultipartFile file1) {
		Result result = new Result();
		logger.info(admin.toString());

		// 用户选择了上传的文件
		if (file1 != null && file1.getSize() > 0) {
			// 获取或创建文件在服务器的保存路径
			String uploadPath = "images/";
			File pathFile = new File(fileRootPath + uploadPath);
			pathFile.mkdirs();
			// 修改上传后的文件名称
			String ofname = file1.getOriginalFilename();
			String fileType = ofname.substring(ofname.lastIndexOf("."));
			String newFileName = UUID.randomUUID() + fileType;
			File outputFile = new File(pathFile, newFileName);

			try {
				// 执行文件上传
				file1.transferTo(outputFile);
				// 上传成功，保存头像的相对地址
				admin.setHeadImage(uploadPath + newFileName);
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		// 取出明文密码进制加密，并设置管理员的默认值
		String salt = PasswordUtils.getSalt();
		String password = PasswordUtils.encode(admin.getPassword(), salt);
		admin.setPassword(password);
		admin.setSalt(salt);
		admin.setFlag(0);
		admin.setStatus(0);
		admin.setHireDate(new Date());

		try {
			boolean ret = adminService.add(admin);
			if (ret) {
				result.setSuccess(Boolean.TRUE);
				result.setErrorMsg("新增成功");
			}
		} catch (JdbootException e) {
			result.setErrorMsg("新增失败");
		}

		return result;
	}

	@PostMapping("/edit")
	@ResponseBody
	public Result doEdit(Admin admin, MultipartFile file1) {
		Result result = new Result();
		logger.info("---->>" + admin.toString());

		// 用户选择了上传的文件
		if (file1 != null && file1.getSize() > 0) {
			logger.info(file1.getOriginalFilename());
			// 获取或创建文件在服务器的保存路径
			String uploadPath = "images/";
			File pathFile = new File(fileRootPath + uploadPath);
			pathFile.mkdirs();
			// 修改上传后的文件名称
			String ofname = file1.getOriginalFilename();
			String fileType = ofname.substring(ofname.lastIndexOf("."));
			String newFileName = UUID.randomUUID() + fileType;
			File outputFile = new File(pathFile, newFileName);

			try {
				// 执行文件上传
				file1.transferTo(outputFile);
				// 上传成功，保存头像的相对地址
				admin.setHeadImage(uploadPath + newFileName);
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		Admin temp = adminService.findById(admin.getId());

		if (admin.getPassword() != null && admin.getPassword().trim().length() > 0) {

			// 取出明文密码进制加密，并设置管理员的默认值
			String salt = PasswordUtils.getSalt();
			String password = PasswordUtils.encode(admin.getPassword().trim(), salt);
			temp.setPassword(password);
			temp.setSalt(salt);
		}

		if (admin.getHeadImage() != null) {
			temp.setHeadImage(admin.getHeadImage());
		}

		temp.setMobile(admin.getMobile());
		temp.setSex(admin.getSex());
		temp.setEmail(admin.getEmail());
		temp.setAddress(admin.getAddress());
		// 超级管理员角色不能修改,在编辑页面不传递角色编号
		if (admin.getRole() != null && admin.getRole().getId() != null) {
			temp.setRole(admin.getRole());
		}

		try {
			boolean ret = adminService.edit(temp);
			if (ret) {
				result.setSuccess(Boolean.TRUE);
				result.setErrorMsg("修改成功");
			}
		} catch (JdbootException e) {
			result.setErrorMsg("修改失败");
		}

		return result;
	}

	@PostMapping("/del")
	@ResponseBody
	public Result delete(@RequestParam(defaultValue = "0", value = "id") Integer id) {
		Result result = new Result();

		logger.info(id.toString());
		try {
			if (id != 0) {
				boolean ret = adminService.deleteById(id);
				if (ret) {
					result.setSuccess(Boolean.TRUE);
					result.setErrorMsg("删除成功");
				} else {
					result.setErrorMsg("修改失败");
				}
			} else {
				result.setErrorMsg("请选择正确的数据");
			}

		} catch (JdbootException e) {
			result.setErrorMsg("修改失败");
		}
		return result;
	}

	@PostMapping("/status")
	@ResponseBody
	public Result doStatus(@RequestParam(defaultValue = "0") Integer id,
			@RequestParam(defaultValue = "2") Integer status) {
		Result result = new Result();
		logger.info(id.toString());
		try {
			boolean ret = adminService.updateStatus(id, status);
			if (ret) {
				result.setSuccess(Boolean.TRUE);
				result.setErrorMsg("修改成功");
			} else {
				result.setErrorMsg("修改失败");
			}
		} catch (JdbootException e) {
			result.setErrorMsg("修改失败");
		}

		return result;
	}

}
